﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace XmlSplitter
{
    public static class Tools
    {
        /// <summary>
        /// init xDoc
        /// set insertToElement property
        /// </summary>
        /// <param name="xml">xml source</param>
        /// <returns>rootElement for new xml</returns>
        public static string PrepareClearRoot(XDocument xDoc, string XmlTag, out XName insertToElement)
        {
            var xd = new XDocument(xDoc);
            
            var xn = GetXName(XmlTag, xd);
            var e1 = xd.Descendants(xn).FirstOrDefault().Parent;
            e1.RemoveNodes();
            insertToElement = e1.Name;
            while(e1 != xd.Root)
            {
                e1 = e1.Parent;
            }
            return e1.ToString();
        }

        public static XName GetXName(string xmlTagName, XDocument xd)
        {
            var parts = xmlTagName.Split(':');
            if (parts.Length == 1) return xmlTagName;
            XNamespace xn = xd.Root.GetNamespaceOfPrefix(parts[0]);
            return XName.Get(parts[1], xn.NamespaceName);
        }

        public static XDocument GetXDoc(string filename, Encoding enc = null)
        {
            if (enc == null) enc = Encoding.Default;
            return XDocument.Parse(File.ReadAllText(filename, enc));
        }
    }
}
